package com.proton.carepatchtemp.activity;

import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;

import com.apkfuns.logutils.LogUtils;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.LimitLine;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.google.gson.reflect.TypeToken;
import com.proton.carepatchtemp.R;
import com.proton.carepatchtemp.base.BaseActivity;
import com.proton.carepatchtemp.constant.Config;
import com.proton.carepatchtemp.constant.Extras;
import com.proton.carepatchtemp.database.table.Report;
import com.proton.carepatchtemp.ui.ChartView.DayAxisValueFormatter;
import com.proton.carepatchtemp.ui.ChartView.MyAxisValueFormatter;
import com.proton.carepatchtemp.ui.ChartView.XYMarkerView;
import com.proton.carepatchtemp.utils.FileUtils;
import com.proton.carepatchtemp.utils.JSONUtils;
import com.proton.carepatchtemp.utils.NetUtils;
import com.proton.carepatchtemp.utils.TastyUtils;
import com.proton.carepatchtemp.utils.ThreadUtils;
import com.proton.carepatchtemp.utils.eventbus.MainEvent;
import com.sdsmdg.tastytoast.TastyToast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

public class ReportPngCreateActivity extends BaseActivity implements OnChartValueSelectedListener {

    ArrayList<Entry> yVals1 = new ArrayList<>();
    ArrayList<Integer> colors = new ArrayList<>();
    private LineChart mBcReportChart;
    private ProgressDialog mProgressDialog;
    private long reportId;
    private Report mReport;

    @Override
    public void dealEvent(MainEvent event) {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_report_png_create);
        if (NetUtils.noNet()) {
            finish();
        }
        if (null == getIntent().getExtras()) {
            TastyUtils.makeTextShort(getString(R.string.get_rpt_info_failed), TastyToast.ERROR);
        } else {
            mReport = (Report) getIntent().getExtras().getSerializable(Extras.REPORT);
            if (null == mReport) {
                TastyUtils.makeTextShort(getString(R.string.get_rpt_info_failed), TastyToast.ERROR);
                finish();
            }
            reportId = mReport.getId();
        }
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setCancelable(false);
        mProgressDialog.setMessage(getString(R.string.loading));
        initView();
        setListener();
        initChart();
        setData();
    }

    private void initChart() {
        mBcReportChart.setOnChartValueSelectedListener(this);
        mBcReportChart.getDescription().setEnabled(false);
        mBcReportChart.setPinchZoom(true);
        mBcReportChart.setScaleYEnabled(false);
        mBcReportChart.setScaleXEnabled(true);
        mBcReportChart.setDrawGridBackground(true);
        mBcReportChart.setDoubleTapToZoomEnabled(false);
        mBcReportChart.setVisibleYRange(34, 42, YAxis.AxisDependency.LEFT);
        mBcReportChart.setDrawBorders(true);
        mBcReportChart.setNoDataText(getString(R.string.have_no_data));
        DayAxisValueFormatter xAxisFormatter = new DayAxisValueFormatter(mBcReportChart);
        xAxisFormatter.setStartTime(mReport.getStarttime());

        XAxis xAxis = mBcReportChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setValueFormatter(xAxisFormatter);
        xAxis.enableGridDashedLine(10f, 10f, 0f);

        IAxisValueFormatter custom = new MyAxisValueFormatter();

        YAxis leftAxis = mBcReportChart.getAxisLeft();
        leftAxis.setAxisMinimum(30.00f);
        leftAxis.setAxisMaximum(42.00f);

        LimitLine limitLine = new LimitLine(37.2F, 37.2 + "℃");
        limitLine.setTextSize(10f);
        limitLine.enableDashedLine(10f, 10f, 0f);
        limitLine.setTextColor(ContextCompat.getColor(this, R.color.orange));
        limitLine.setLineColor(ContextCompat.getColor(this, R.color.orange));

        leftAxis.addLimitLine(limitLine);
        leftAxis.setLabelCount(8, false);
        leftAxis.setValueFormatter(custom);
        leftAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);
        leftAxis.setSpaceTop(15f);

        YAxis rightAxis = mBcReportChart.getAxisRight();
        rightAxis.setEnabled(false);

        Legend l = mBcReportChart.getLegend();
        l.setEnabled(false);

        XYMarkerView mv = new XYMarkerView(this, xAxisFormatter);
        mv.setChartView(mBcReportChart); // For bounds control
        mBcReportChart.setMarker(mv); // Set the marker to the chart

    }

    private void setData() {
        mProgressDialog.show();
        ThreadUtils.runOnOtherThread(() -> {
            String fpString = "";
            JSONObject fpJsonObj = null;
            if (!FileUtils.getJson_filepath().contains(FileUtils.json_filepath + File.separator + reportId)) {
                LogUtils.e("have no filePath");
                if (TextUtils.isEmpty(mReport.getFilepath())) {
                    return;
                }
                fpString = FileUtils.downLoadFromUrl(mReport.getFilepath(), String.valueOf(mReport.getId()), FileUtils.json_filepath);
            } else {
                try {
                    fpString = FileUtils.readJSONFile(FileUtils.json_filepath, mReport.getId());
                } catch (IOException e) {
                    e.printStackTrace();
                    return;
                }
            }


            //  第一阶段文件转换为JSON对象
            try {
                fpJsonObj = new JSONObject(fpString);
            } catch (JSONException e) {
                fpJsonObj = null;
                e.printStackTrace();
            }

            yVals1.clear();
            colors.clear();

            JSONArray array = null;
            try {
                array = fpJsonObj.getJSONArray("floats");
            } catch (JSONException e) {
                e.printStackTrace();
            }

            List<Float> list = new ArrayList<>();
            list.clear();

            Type listType = new TypeToken<ArrayList<Float>>() {
            }.getType();

            list = JSONUtils.getObj(array.toString(), listType, "yyyy-MM-dd");
            for (int i = 1; i < list.size(); i++) {
                if (null != list.get(i - 1)) {
                    float val = list.get(i - 1);
                    yVals1.add(new BarEntry(i, val));
                    if (val > 37.50f) {
                        colors.add(ContextCompat.getColor(this, android.R.color.holo_red_light));
                    } else if (val < 35.00f) {
                        colors.add(ContextCompat.getColor(this, R.color.blueDeep));
                    } else {
                        colors.add(ContextCompat.getColor(this, R.color.blueCenter));
                    }
                }
            }

            LineDataSet set1;

            if (mBcReportChart.getData() != null &&
                    mBcReportChart.getData().getDataSetCount() > 0) {
                set1 = (LineDataSet) mBcReportChart.getData().getDataSetByIndex(0);
                set1.setValues(yVals1);

                mBcReportChart.getData().notifyDataChanged();
                mBcReportChart.notifyDataSetChanged();
            } else {
                set1 = new LineDataSet(yVals1, "The year 2017");
                set1 = new LineDataSet(yVals1, "The year 2017");
//            set1.setColors(ColorTemplate.MATERIAL_COLORS);
                set1.setDrawFilled(true);
                set1.setDrawCircles(false);
                set1.disableDashedLine();
//                set1.enableDashedLine(10f, 5f, 0f);
                set1.enableDashedHighlightLine(10f, 5f, 0f);
                set1.setColor(Color.TRANSPARENT);
                set1.setCircleColor(Color.BLACK);
                set1.setLineWidth(0f);
//                set1.setCircleRadius(3f);
                set1.setDrawCircleHole(false);
                set1.setDrawValues(false);
//                set1.setValueTextSize(9f);
                set1.setDrawFilled(true);
                set1.setFormLineWidth(1f);
                set1.setFormLineDashEffect(new DashPathEffect(new float[]{10f, 5f}, 0f));
                set1.setFormSize(15.f);

//            set1.setColors(ColorTemplate.MATERIAL_COLORS);

                ArrayList<ILineDataSet> dataSets = new ArrayList<>();
                dataSets.add(set1);

                Drawable drawable = ContextCompat.getDrawable(this, R.drawable.line_chart);
                drawable.setAlpha(Config.CHART_ALPHA);
                set1.setFillDrawable(drawable);

                LineData data = new LineData(dataSets);
                data.setValueTextSize(10f);
//            data.setValueTypeface(mTfLight);
//                data.setBarWidth(0.9f);
                data.setDrawValues(false);
                mProgressDialog.dismiss();
                mBcReportChart.setData(data);
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                Bitmap b = mBcReportChart.getChartBitmap();

                FileOutputStream stream = null;
                try {
                    stream = new FileOutputStream(FileUtils.getReport() + File.separator + reportId
                            + ".png");
            /*
             * Write bitmap to file using JPEG or PNG and 40% quality hint for
             * JPEG.
             */
                    b.compress(Bitmap.CompressFormat.PNG, 40, stream);
                    stream.flush();
                    stream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                setResult(RESULT_OK);
                finish();
            }

        });
    }

    @Override
    protected void setListener() {

    }

    @Override
    public void onEventMainThread(MainEvent event) {

    }

    private void initView() {
        mBcReportChart = findViewById(R.id.bc_report_chart);
    }

    @Override
    public void onValueSelected(Entry e, Highlight h) {
    }

    @Override
    public void onNothingSelected() {

    }
}
